package com.cheerful.blog.schedule;

import com.cheerful.blog.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

import static com.cheerful.blog.config.constant.CacheEnum.VIEW_NUMS_PREFIX;

/**
 * @author: Wang Zhifu
 * @create: 2022/2/11 23:57
 * @Description:
 */
@Slf4j
@Component
public class ArticleSchedule {
    @Autowired
    ArticleService articleService;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    /**
     * 每天两点，把redis里面的值更新到db
     */
    @Scheduled(cron = "0 0 10 * * ?")
    public void viewNumUpdate(){
        Set<String> keys = redisTemplate.keys(VIEW_NUMS_PREFIX + "*");
        if (keys != null && !keys.isEmpty()){
            for (String key : keys) {
                Integer viewNums = (Integer) redisTemplate.opsForValue().get(key);
                Long id=Long.parseLong(key.substring(key.lastIndexOf(":")+1));
                articleService.updateViewNums(id,viewNums);
                redisTemplate.delete(key);
            }
            log.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"---更新缓存到db");
        }
    }
}
